package com.sgai.zero_robot.database;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;


import java.util.List;

@Dao
public interface ZeroDetectionDao {
    @Transaction
    default void upsert(ZeroDetectionEntity zeroDetectionEntity) {
        ZeroDetectionEntity zeroDetection = findByValue(zeroDetectionEntity.getLineName(),
                zeroDetectionEntity.getTowerNum(),
                zeroDetectionEntity.getInstall(),
                zeroDetectionEntity.getPhase(),
                zeroDetectionEntity.getInsulator(),
                zeroDetectionEntity.getPosition());
        if (zeroDetection == null) {
            insert(zeroDetectionEntity);
        } else {
            zeroDetectionEntity.setId(zeroDetection.getId());
            update(zeroDetectionEntity);
        }
    }

    // 辅助方法：具体信息查询
    @Query("SELECT * FROM detection_table WHERE lineName = :lineName AND towerNum = :towerNum AND install = :install AND phase = :phase AND insulator = :insulator AND position = :position LIMIT 1")
    ZeroDetectionEntity findByValue(String lineName,String towerNum,int install,int phase,int insulator,int position);
    // 基本插入方法
    @Insert
    void insert(ZeroDetectionEntity zeroDetectionEntity);

    // 基本更新方法
    @Update
    void update(ZeroDetectionEntity zeroDetectionEntity);
    @Query("SELECT * FROM detection_table")
    List<ZeroDetectionEntity> getAll();

    // 辅助方法：具体信息查询
    @Query("SELECT * FROM detection_table WHERE lineName = :lineName AND towerNum = :towerNum AND install = :install AND phase = :phase AND insulator = :insulator")
    List<ZeroDetectionEntity> getByValue(String lineName,String towerNum,int install,int phase,int insulator);

    /**
     * 通过lineName、towerNum和install三个参数删除数据
     * @param lineName 线路名称
     * @param towerNum 塔号
     * @param install 安装信息
     * @return 删除的行数
     */
    @Query("DELETE FROM detection_table WHERE lineName = :lineName AND towerNum = :towerNum AND install = :install")
    int deleteByParams(String lineName, String towerNum, int install);
    @Delete
    int delete(List<ZeroDetectionEntity> zeroDetectionEntities);
    @Query("DELETE FROM detection_table")
    void deleteAll();
}
